<?php
//需求：有个课程管理，课程分为演讲和研讨会，收费也分为固定收费和按时间收费
//第一版改进 但是在父类中增加了条件语句（并不完美）
/*abstract class Lesson{
    protected $duration;
    const FIXED = 1;
    const TIMED = 2;
    private $costType;
    public function __construct($duration,$costType=1)
    {
        $this->duration = $duration;
        $this->costType = $costType;
    }

    public function cost(){
        switch($this->costType){
            case self::TIMED:
                return (5*$this->duration);
                break;
            case self::FIXED:
                return 30;
                break;
            default:
                $this->costType = self::FIXED;
                return 30;
        }
    }

    public function chargeType(){
        switch($this->costType){
            case self::TIMED:
                return '每小时收费';
                break;
            case self::FIXED:
                return '固定收费';
                break;
            default:
                $this->costType = self::FIXED;
                return '固定收费';
        }
    }
}

class Lecture extends Lesson{

}

class Seminar extends Lesson{

}

$lecture = new Lecture(5,Lesson::FIXED);
print $lecture->cost()."({$lecture->chargeType()})\n";

$seminar = new Seminar(5,Lesson::TIMED);
print $seminar->cost()."({$seminar->chargeType()})\n";*/


//第二版 使用策略模式解决（包含委托）
abstract class Lesson
{
    protected $duration;
    private $costStrategy;

    public function __construct($duration, CostStrategy $costStrategy)
    {
        $this->duration = $duration;
        $this->costStrategy = $costStrategy;
    }

    public function cost()
    {
        return $this->costStrategy->cost($this);
    }

    public function chargeType(){
        return $this->costStrategy->chargeType();
    }

    public function getDuration(){
        return $this->duration;
    }


}
class Lecture extends Lesson{

}

class Seminar extends Lesson{

}

abstract class CostStrategy{
    abstract public function cost(Lesson $lesson);
    abstract public function chargeType();
}

class TimedCostStrategy extends CostStrategy{
    public function cost(Lesson $lesson)
    {
        return $lesson->getDuration() * 5;
    }

    public function chargeType()
    {
        return '按小时收费';
    }
}

class FiexdCostStrategy extends CostStrategy{
    public function cost(Lesson $lesson)
    {
        return 30;
    }

    public function chargeType()
    {
        return '固定收费';
    }
}

$lessons[] = new Lecture(4,new TimedCostStrategy());
$lessons[] = new Seminar(4,new FiexdCostStrategy());

foreach($lessons as $lesson){
    print '课程收费：'.$lesson->cost();
    print '收费类型：'.$lesson->chargeType()."\n";
}


